// pages/pay/pay.js
const app = getApp()
const WXAPI = require("../../api/api")
Page({
  data: {
    nvabarData: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: '确认付款', // 导航栏 中间的标题
      textColor: '#333', // 标题颜色
      bgColor: '#fff', // 导航栏背景颜色
      isloading: true,
      isColor: true,
    },
    nvabarDataSu: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: '确认付款', // 导航栏 中间的标题
      textColor: '#333', // 标题颜色
      bgColor: '#fff', // 导航栏背景颜色
      backUrl: '/pages/userMarket/userMarket'
    },
    //创建订单需要的参数
    payClient: "1", //支付客户端 1 微信 2 支付宝
    merchantId: '', //商户id
    amount: '', //输入金额
    payAmount: '0.00', //实际支付金额
    customerCouponId: '', //客户优惠券id（优惠券抵扣时传） 
    walletIds: [], //钱包id数组（使用积分抵扣时传）
    cardPayMoney: 0, //卡支付金额
    cardId: '', //选择卡ID
    remark: '', //备注
    payScene: '', //支付场景(微信支付时必传) 1 扫码支付 2 直接购买
    assetId: '', //资产id（用户从消费页面进来携带）
    useWalletInfos: [],
    code: '',
    giveMoney: 0, //赠送金额
    cardAssetId: '', //购买安心卡ID
    isActivity: false, //是否购买安心卡


    //页面其他参数
    
    _options: {},
    
    imgHttp: app.globalData.imgHttp, //图片前缀
    qrCodeUrl: '',
    pageData: {}, //支付页面信息
    cardData: {}, //选中卡后传过来的值
    cardList: [],
    mindCardList: [], //安心卡
    mindCardShow: false,//安心卡弹窗
    selCardMoney: 0,//选择用卡后需要支付的金额
    isHasCard: '', //是否可以选可用卡
    cardShow: false, //卡弹窗
    selCard: false,//是否勾选卡
    discountMoney: 0, //折扣金额
    discountNum: '', //折扣
    totalPrice: 0,//总价
    appid: app.globalData.appid,
    phone: '',
    payShow: false, //可以点击确定支付创建订单
    payKong: false, //商家没有入驻
    selected: true, //
    anonymity: '2', //1 匿名用户 2 非匿名用户
    isWx: '', //微信扫码进来
    countdown: 60,
    orderId: '',
    select_an_card:{},
    theShow: false,//本次消费即可使用 是否显示
    cardBalance: 0,//卡内余额
    ismaidian: false,
    deleteToken: false,
    orderManageId: '', //去掉订单id
    keyCodeShow: false,
    wxUrl: '',
  },
  onLoad: function (options) {
    
    this.setData({
      _options: options,
      mobbleBottom: app.mobile.mobbleBottom,
     
    })
    var isWx = options.isWx
    
    this.setData({
      isWx: isWx,
    })
    this.dialog = this.selectComponent("#auth_dialog");
    var token = wx.getStorageSync('token')
    console.log("哈哈哈啊哈哈啊哈", token)
    if (token == '') {
      this.login('no')
      // this.dialog.showPhone()
      return false
    }
    console.log("拒绝授权")
    //微信客户端扫码支付
    var wxUrl = decodeURIComponent(options.q)
    if (wxUrl && wxUrl != 'undefined') {
      var num = wxUrl.indexOf("?")
      wxUrl = wxUrl.substring(num + 1); //
      wxUrl = wxUrl.split("code=");
      wxUrl = wxUrl[1]
      wxUrl = JSON.parse(wxUrl)
      console.log("微信扫二维码支付", )
      this.setData({
        qrCodeUrl: wxUrl.param,
        payScene: 1,
        isWx: true,
      })
      this.getParCollectionQrCodeUrl()
    }
    //蜜链盟券立即消费进入
    var scanUrl = options.scanUrl
    var assetId = options.assetId
    
    var merchantId = options.merchantId
    // var merchantId = '1427896779155771394'
    if (merchantId) {
      this.setData({
        merchantId: merchantId,
        assetId: assetId,
        payScene: 2,
      })
      this.getConfirmInfo()
      this.getCard()
    }
    //蜜链盟用户端扫码进入
    // var QRmerchantId = '1384317372986413058'
    var QRmerchantId = options.QRmerchantId
    var staffId = options.staffId != 'undefined' ? options.staffId :'';
    if (QRmerchantId) {
      console.log("扫二维码支付")
      this.setData({
        merchantId: QRmerchantId,
        payScene: 1,
        staffId: staffId,
      })
      this.getConfirmInfo()
      this.getCard()
    }
    this.setNavSize()
  },
  //解析二维码confirmInfo
  getParCollectionQrCodeUrl() {
    const that = this
    var data = {
      qrCodeUrl: this.data.qrCodeUrl,
      // qrCodeUrl:'https://bee.xiaodaiyan.com/pay/uQRxY%2F6Y4pbfVN4%2BbISi5WEG2fcys%2Beg9h2%2B0dfXuU8%3D',  
    }
    WXAPI.parCollectionQrCodeUrl(data, (res) => {
      const data = res.result
      console.log("解析二维码", res)
      if (res.code === 200) {
        this.setData({
          merchantId: data.merchantId,
        })
        this.getConfirmInfo()
        this.getCard()
      } else {
        this.setData({
          payKong: true
        })
      }
    })
  },
  //支付页面信息
  getConfirmInfo() {
    const that = this
    var data = {
      merchantId: this.data.merchantId,
    }
    WXAPI.confirmInfo(data, (res) => {
      const data = res.result
      console.log("支付页面信息", res)
      if (res.code === 200) {
        this.setData({
          pageData: res.result,
        })
      }

    })
  },
  //初始化参数
  init(){
    var amount = this.data.amount
    var cardAssetId = this.data.cardAssetId
    console.log('cardAssetId',cardAssetId)
    this.setData({
      payAmount: amount,
      totalPrice: amount,//总价
      walletIds: [],//折扣
      discountNum: '', //清空折扣
      selCard: false,//不勾选卡
      cardId: '',//选择卡ID
      discountMoney: 0,//折扣金额
      cardData: {}, //清空选中的卡数据
      cardPayMoney: 0, //卡支付金额清零
      giveMoney: 0, //赠送金额
      cardAssetId: '', //购买安心卡ID
      isActivity: false, //是否购买安心卡
      // payShow: false,
      select_an_card:{},//安心卡数据
      cardBalance: 0,//卡支付金额90u.,              
    })
    if(this.data.cardAssetId != cardAssetId){
      wx.showToast({
        title: '购卡操作已失效,请重新勾选卡',
        icon: 'none'
      })
    }
  },
  //获取卡
  getCard() {
    var data = {
      merchantId: this.data.merchantId
    }
    WXAPI.cardPayDetail(data, (res) => {
      var isHasCard = ''
      if (res.result.appCustomerCardPayDTOList.length > 0) {
        isHasCard = true
      } else {
        isHasCard = false
      }
      this.setData({
        cardList: res.result.appCustomerCardPayDTOList,//拥有的卡
        mindCardList: res.result.appCustomerCardActivityDTOList,
        //推荐的安心卡
        contractPath: res.result.contractPath,
        isHasCard: isHasCard,
      })
    })
  },
  //卡弹窗
  handleCard() {
    this.setData({
      cardShow: true,
    })
  },
  //卡弹窗关闭
  handleChose() {
    this.setData({
      cardShow: false,
    })
  },
  //卡弹窗确认后传过来所选卡的信息
  handleConfirm(e) {
    console.log('e', e.detail)
    this.setData({
      cardData: e.detail,
      payAmount: this.data.TicketPayAmount,
      cardType: e.detail.cardType
    })

  },
  //是否选择了卡
  handleselCard(e) {
    console.log('e', e.detail)
    this.setData({
      selCard: e.detail
    })
    this.calculateCard()
  },
  //输入金额变化
  changeAmount(e) {
    var amount = this.PointNum(e.detail.value)
    var totalPrice = parseFloat(amount)
    console.log("钱变化",totalPrice)
    
    this.setData({
      amount: amount,
      totalPrice: Math.round(totalPrice * 100) / 100,
    })
    this.init()
  },
  //输入金额框获得焦点
  focusAmount(){
    console.log(1111111111)
    wx.hideKeyboard();
    this.setData({
      keyCodeShow: !this.data.keyCodeShow,
    })
  },
  handleChoseKey(){
    this.setData({
      keyCodeShow: false,
    })
  },
  //输入金额框失去焦点
  hangdleAmount() {
    console.log('失去焦点')
    var amount = this.data.amount
    var cardList = this.data.cardList
    if (amount == '' ||  amount == 0 ) {
      if(this.data.mindCardList.length == 0 ){
        this.setData({
          payShow: false
        })
      }
    } else {
      if (cardList.length == 1) {
        this.setData({
          cardData: cardList[0],
          selCard: true,
        })
        this.calculateCard()
      }
      this.setData({
        payShow: true,
      })
    }
  },
  //选择卡后执行的计算
  calculateCard() {
    var payAmount = this.data.amount
    var balanceMoney = parseFloat(this.data.cardData.balanceMoney)
    var cardPayMoney = this.data.cardPayMoney //股东卡抵扣金额
    var selCardMoney = this.data.selCardMoney //选择卡后需要支付的金额
    var discountMoney = 0 //折扣金额
    var cardBalance = this.data.cardBalance//卡内余额
    if (this.data.cardData.discount) { //有折扣
      var discount = parseFloat(this.data.cardData.discount) / 10 //卡折扣
    } else { //没折扣
      var discount = 1 //卡折扣
    }
    console.log('折扣', discount)
    console.log('折扣', this.data.selCard)
    if (this.data.selCard) {
      if (balanceMoney > payAmount * discount) {
        cardPayMoney = payAmount * discount
        selCardMoney = 0
        discountMoney = discountMoney + (payAmount - payAmount * discount)
        cardBalance = balanceMoney - payAmount * discount//卡余额还剩多少
      } else if (balanceMoney <= payAmount * discount) {
        cardPayMoney = balanceMoney
        cardBalance = 0//卡余额还剩多少
        if (this.data.cardData.discount) {
          selCardMoney = Math.round(payAmount * discount * 100) / 100 - balanceMoney
          console.log('实际支付金额', selCardMoney)
        } else {
          selCardMoney = payAmount - balanceMoney
        }
        discountMoney = discountMoney + (payAmount - payAmount * discount)
      }
      cardPayMoney = this.roundFixed(cardPayMoney, 2)
      this.setData({
        payAmount: Math.round(selCardMoney * 100) / 100,
        cardPayMoney: cardPayMoney,
        discountMoney: Math.round(discountMoney * 100) / 100,
        cardId: this.data.cardData.id,
        discountNum: this.data.cardData.discount,
        cardBalance: Math.round(cardBalance * 100) / 100,
      })
    } else {
      console.log('无卡')
      var payAmount = this.data.amount
      this.setData({
        payAmount: payAmount,
        cardPayMoney: 0,
        discountMoney: discountMoney,
        cardId: '',
        discountNum: '',
      })
    }
  },
  //选择安心卡
  handlemindCard(e){
    if(e){
      if(e.type == 'tap'){
        var item = e.currentTarget.dataset.item
      }
    }
    console.log('88888888888',e)
    var assetId = item.assetId
    var cardAssetId = this.data.cardAssetId
    if (cardAssetId == assetId) {//取消购卡
      this.setData({
        cardAssetId: '',
      })
    } else { //购买卡
      this.login('yes')
      this.setData({
        cardAssetId: assetId,
        mindCardShow:true,
      })
    }
  },
  //查看更多优惠
  handleMore(){
    this.setData({
      mindCardShow: true,
    })
  },
  //更多优惠关闭
  handleMindChose(){
    this.setData({
      mindCardShow: false,
      cardAssetId:'',
    })
  },
  amountData(e){
    var amountData = e.detail
    if(amountData){
      this.setData({
        payShow: true,
      })
    }else{
      this.setData({
        payShow: false,
      })
    }
    this.setData({
      amount: amountData,
      payAmount: amountData,
    })
    console.log('amountData',amountData)
  },
  //勾选用户协议
  handleReading() {
    this.setData({
      selected: !this.data.selected
    })
  },
  //查看合同
  handleContract(e) {
    var url = this.data.imgHttp + e.currentTarget.dataset.url
    var index = url.lastIndexOf("\.");
    var type = url.substring(index + 1, url.length);
    wx.downloadFile({
      url: url,
      header: {},
      success: function (res) {
        var filePath = res.tempFilePath;
        console.log(filePath);
        wx.openDocument({
          filePath: filePath,
          fileType: type,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function (res) {
            console.log("1111111111111", res);
          },
          complete: function (res) {
            console.log("22222222222222", res);
          }
        })
      },
      fail: function (res) {
        console.log('文件下载失败');
      },
      complete: function (res) {},
    })

  },

  //匿名支付获取token
  getToken() {
    var code = this.data.code
    console.log('code', code)
    var data = {
      code: code,
      appid: app.globalData.appid,
    }
    WXAPI.silentAuthorization(data, (res) => {
      const data = res.result
      console.log("获取token", res)
      if (res.code === 200) {
        wx.setStorageSync('token', data.token)
        this.onLoad(this.data._options)
        this.setData({
          anonymity: data.anonymity,
        })
      }
    })
  },
  //授权手机号码
  getPhoneNumber: function(e) {     
    let that = this;
    console.log(e.detail.errMsg)     
    console.log(e.detail.iv)     
    console.log(e.detail.encryptedData)    
    console.log(e.detail.errMsg) 
    if (e.detail.errMsg == 'getPhoneNumber:ok'){    
      console.log("点击事件",that.data.code)
      let data = {
        appid: that.data.appid,
        code: that.data.code,
        encryptedData:e.detail.encryptedData,
        iv:e.detail.iv,
        source: app.globalData.source,//用户来源
      }
       WXAPI.newgetPhone( 'no',data ,(res) =>{
        let data = res.result
        if(res.result){
          if(data.token){
            wx.setStorageSync('token',data.token)
          }
          that.setData({
            deleteToken: true,
          })
          that.handlePay()
        }
        
      })
    }else if(e.detail.errMsg == 'getPhoneNumber:fail user deny') {  
      //ios拒绝授权  
      wx.showModal({
        content: '为了更好的保障您的权益，购买预付卡需您授权获取您的手机号',
        confirmText: '我知道了',
        confirmColor: '#FF5800',
        showCancel: false,
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    
    }else if (e.detail.errMsg == 'getPhoneNumber:fail:user deny'){  
      //安卓拒绝授权    
      
    }    
  },  
  login(type) {
    // 登录 
    let that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          that.setData({
            code: res.code
          })
          console.log('res.code',res.code)
          if(type == 'no'){
            that.getToken()
          }
          console.log('获取code', that.data.code)
        } else {
          console.log('获取code失败', res.errMsg)
        }
      }
    })
  },
  //数字格式化
  PointNum(obj) {
    var $this = this;
    obj = obj.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    obj = obj.replace(/^\./g, ""); //验证第一个字符是数字
    obj = obj.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
    obj = obj.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj = obj.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    return obj;
  },
  //数字格式化
  roundFixed(num, fixed) {
    var pos = num.toString().indexOf('.'),
      decimal_places = num.toString().length - pos - 1,
      _int = num * Math.pow(10, decimal_places),
      divisor_1 = Math.pow(10, decimal_places - fixed),
      divisor_2 = Math.pow(10, fixed);
    return Math.round(_int / divisor_1) / divisor_2;
  },
  //取消订单
  cancelOrder(e) {
    var that = this
    var data = {
      id: that.data.orderManageId
    }
    WXAPI.cancelOrder(data, (res) => {
      const data = res.result
      if (res.code === 200) {
        that.getCard()
      }
    })
  },
  //创建订单
  handlePay() {
    const that = this
    if (!this.data.selected && this.data.isActivity) {
      wx.showToast({
        title: '请勾选购卡合同',
        icon: 'none'
      })
      return false
    }
    var data = {
      payClient: this.data.payClient, //支付客户端 1 微信 2 支付宝
      merchantId: this.data.merchantId, //商户id
      amount: this.data.amount, //金额
      payAmount: this.data.payAmount, //实际支付金额
      customerCouponId: this.data.customerCouponId, //客户优惠券id（优惠券抵扣时传） 
      walletIds: this.data.walletIds, //钱包id数组（使用积分抵扣时传）
      cardMoney: this.data.cardPayMoney,
      cardId: this.data.cardId, //   卡ID
      assetId: this.data.assetId, //资产id（用户从消费页面进来携带）
      remark: this.data.remark, //备注
      payScene: this.data.payScene, //支付场景(微信支付时必传) 1 扫码支付 2 直接购买
      useWalletInfos: this.data.useWalletInfos,
      wxCode: this.data.code,
      giveMoney: this.data.giveMoney, //赠送金额
      cardAssetId: this.data.cardAssetId, //购买安心卡ID
      isActivity: this.data.isActivity, //是否购买安心卡
      staffId: this.data.staffId
    }
    console.log("创建订单", data)
    WXAPI.createOrder(data, (res) => {
      wx.showLoading({
        title: '支付中...',
        mask: 'true',
      })
      const data = res.result
      console.log("创建订单", res)
      if (res.code === 200) {
        this.data.orderManageId = res.result.orderManageId
        if (data.orderType == 1) {
          if (data.client == 1) {
            //微信支付
            wx.requestPayment({
              'timeStamp': data.timeStamp,
              'nonceStr': data.nonceStr,
              'package': data.package,
              'signType': data.signType, //MD5
              'paySign': data.paySign,
              'success': function (res) {
                wx.hideLoading()
                console.log('支付成功', res)
                console.log(res)
                if (res.errMsg == 'requestPayment:ok') {
                  wx.showToast({
                    title: '支付成功',
                  })
                  that.setData({
                    orderId: data.orderId
                  })
                  that.getCardPayorder()
                }
              },
              'fail': function (res) {
                that.cancelOrder()
                wx.hideLoading({
                  success: (res) => {
                    wx.showToast({
                      title: '支付失败',
                      icon: 'none'
                    })
                  },
                })
                console.log('支付失败或取消支付', res)
                // that.onLoad()
                // that.getCard()
                that.init()
                if (that.data.amount == '' && that.data.mindCardList.length > 0) {
                  that.setData({
                    payShow: false,
                  })
                }
              },
              'complete': function (res) {
                console.log('支付完成', res)
              }
            })
          } else if (data.client == 2) {
            //支付宝
          }

        } else if (data.orderType == 2) {
          //0元订单
          wx.redirectTo({
            url: '/pages/pay/paySuccess/paySuccess?orderId=' + data.orderId+'&anonymity=' + that.data.anonymity +'&deleteToken='+ that.data.deleteToken,
          })
        }
      }else{
        wx.hideLoading()
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
      }


    })
  },
  //购卡订单支付结果
  getCardPayorder() {
    const that = this
    console.log("that.data.anonymit", that.data.anonymit)
    this.setData({
      timer: setInterval(function () { //这里把setInterval赋值给变量名为timer的变量
        that.data.countdown--;
        var data = {
          orderId: that.data.orderId,
        }
        WXAPI.payResult(data, (res) => {
          const data = res.result
          console.log("获取支付结果", data.isPay)
         
          if (data.isPay) {
            wx.redirectTo({
              url: '/pages/pay/paySuccess/paySuccess?orderId=' + that.data.orderId + '&anonymity=' + that.data.anonymity +'&deleteToken='+ that.data.deleteToken,
            })
            clearInterval(that.data.timer);
          }
        })
        that.setData({
          countdown: that.data.countdown,
        })
        if (that.data.countdown == 0) {
          clearInterval(that.data.timer);
          that.setData({
            countdown: 60,
          })
        }
      }, 1000)
    })

  },
  // 通过获取系统信息计算导航栏高度
  setNavSize: function() {
    var that = this
        , sysinfo = wx.getSystemInfoSync()
        , statusHeight = sysinfo.statusBarHeight
        , isiOS = sysinfo.system.indexOf('iOS') > -1
        , navHeight;
    if (!isiOS) {
        navHeight = 48;
    } else {
        navHeight = 44;
    }
    console.log('statusHeight',statusHeight)
    console.log('navHeight',navHeight)
    that.data.top = statusHeight + navHeight
    that.setData({
        status: statusHeight,
        navHeight: navHeight
    })
  },
  //返回上一级
  handleBack(){
    if(this.data.anonymity == 1){
      wx.clearStorageSync()
      console.log('清空token',)
    }
    wx.navigateBack({
      delta: 1
    });
  },
  //关闭页面
  chosePage(){
    if(this.data.anonymity == 1){
      wx.clearStorageSync()
      console.log('清空token',)
    }
    wx.reLaunch({
      url: '/pages/userMarket/userMarket',
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
})